//
//  PictureSelectController.swift
//  SinaWeibo
//
//  Created by 小果 on 16/2/21.
//  Copyright © 2016年 小果. All rights reserved.
//

import UIKit
private let PictureSelectorCellID = "PictureSelectorCellID"
private let HMMaxPictureCount = 20
class PictureSelectController: UICollectionViewController,PictureSelectorCellDelegate {
    private lazy var pictures = [UIImage]()
    private var currentIndex = 0
    // MARK: - 搭建界面
    init() {
        let layout = UICollectionViewFlowLayout()
        
        super.init(collectionViewLayout: layout)
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor(white: 0.97, alpha: 1.0)
        
        // 注册可重用 cell
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: PictureSelectorCellID)
    }
    
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count + (pictures.count == HMMaxPictureCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureSelectorCellID, forIndexPath: indexPath) as! PictureSelectorCell
        cell.pictureDelegate = self
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
        
        return cell
    }
    
    /// 选择照片
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("无法访问相册")
            return
        }
        currentIndex = indexPath.item
        
        // 访问相册
        let vc = UIImagePickerController()
        vc.delegate = self
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    // MARK: - PictureSelectorCellDelegate
    private func pictureSelectorCellClickremoveBtn(cell: PictureSelectorCell) {
        // 根据 cell 获得当前的索引
        if let indexPath = collectionView?.indexPathForCell(cell) where indexPath.item < pictures.count {
            pictures.removeAtIndex(indexPath.item)
            collectionView?.reloadData()
        }
    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PictureSelectController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
           func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleImageToWidth(300)
        // 用户选中了一张照片
        if currentIndex < pictures.count {
            pictures[currentIndex] = scaleImage
        } else {
            pictures.append(scaleImage)
        }
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

/// 照片 Cell 的协议
private protocol PictureSelectorCellDelegate: NSObjectProtocol {
    func pictureSelectorCellClickremoveBtn(cell: PictureSelectorCell)
}

/// 照片选择 Cell
private class PictureSelectorCell: UICollectionViewCell {
    var image: UIImage? {
        didSet {
            if image != nil {
                pictureBtn.setImage(image, forState: .Normal)
            } else {
                // 显示默认的加号图片
                pictureBtn.setImage(UIImage(named: "addBtn"), forState: UIControlState.Normal)
            }
            removeBtn.hidden = (image == nil)
        }
    }
    
    /// 定义代理
    weak var pictureDelegate: PictureSelectorCellDelegate?
    
    /// 点击删除按钮
    @objc private func clickRemove() {
        pictureDelegate?.pictureSelectorCellClickremoveBtn(self)
    }
    
    /// 切记： frame是根据 layout 的 itemSize 来的
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(pictureBtn)
        contentView.addSubview(removeBtn)
        
        // 布局
        pictureBtn.frame = bounds
        
        removeBtn.translatesAutoresizingMaskIntoConstraints = false
        let viewDict = ["btn": removeBtn]
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[btn]-0-|", options: [], metrics: nil, views: viewDict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[btn]", options: [], metrics: nil, views: viewDict))
    
        pictureBtn.userInteractionEnabled = false
        
        // 添加监听方法
        removeBtn.addTarget(self, action: "clickRemove", forControlEvents: .TouchUpInside)
        pictureBtn.imageView!.contentMode = UIViewContentMode.ScaleAspectFill
    }
    
    // MARK: - 懒加载控件
    /// 添加照片按钮
    private lazy var pictureBtn: UIButton = UIButton(imageName: "addBtn")
    /// 删除照片按钮
    private lazy var removeBtn: UIButton = UIButton(imageName: "deleteBtn")
    
}
